package com.pw.study.flink.source;

import com.pw.study.flink.entities.WaterSensor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

public class CustomSource {
    public static void main(String[] args) {
        dealCustom();

    }

    private static void dealCustom() {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.addSource(new SocketSource("hadoop162",9999)).print();

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static class SocketSource implements SourceFunction<WaterSensor> {
        private final String host;
        private final int port;
        private boolean isCancel;

        public SocketSource(String host, int port) {
            this.host = host;
            this.port = port;
        }

        @Override
        public void run(SourceContext<WaterSensor> ctx) throws Exception {
            Socket socket = new Socket(host, port);
            InputStream is = socket.getInputStream();
            InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8);
            BufferedReader buffer = new BufferedReader(reader);
            String line = buffer.readLine();
            while (!isCancel && line != null) {
                System.out.println("line:"+line);
                String[] data = line.split(",");

                ctx.collect(new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2])));
                line = buffer.readLine();
            }
        }

        @Override
        public void cancel() {
            isCancel = true;
        }
    }
}

